<script setup lang="ts">
import {
  mdiArrowLeft,
  mdiArrowRight,
  mdiCellphone,
  mdiClose,
  mdiDotsVertical,
  mdiExport,
  mdiHomeOutline,
  mdiImport,
  mdiMinus,
  mdiMonitorSmall,
  mdiPinOffOutline,
  mdiPinOutline,
  mdiRefresh,
  mdiWindowMaximize,
  mdiWindowRestore
} from '@mdi/js'

import { useI18n } from 'vue-i18n'
import { showContextMenu } from '@/utils/contextMenuHelper'
import { EscPriority, register } from '@/utils/esc-manager'

import FindInPage from '@/components/FindInPage.vue'
import { layoutOn } from '@/utils/layoutEvent'

const props = defineProps<{
  isLeft?: boolean // 是否为左侧标签栏
  tab: F2.tab.Entity
  homeUrl?: string
  isCollapsed?: boolean
}>()

// 获取工具栏配置
const toolbarConfig = computed(() => props.tab.toolbarConfig)
const isPinned = computed(() => props.tab.sidebarConfig?.isPinned)
const webContentsId = computed(() => props.tab.webContentsId)

/**
 * 是否显示图标
 * - undefined/true: 显示默认图标
 * - false: 不显示
 * - string: 显示自定义图标
 */
const shouldShowIcon = computed(() => {
  const config = toolbarConfig.value?.icon
  return config !== false
})

/**
 * 是否显示标题
 * - undefined/true: 显示默认标题
 * - false: 不显示
 * - string: 显示自定义标题
 */
const shouldShowTitle = computed(() => {
  const config = toolbarConfig.value?.title
  return config !== false
})

/**
 * 实际显示的图标
 * - string: 使用自定义图标
 * - 其他: 使用默认图标
 */
const displayIcon = computed(() => {
  const config = toolbarConfig.value?.icon
  if (typeof config === 'string') {
    return config
  }
  return props.tab.icon
})

/**
 * 实际显示的 favicon
 * - 如果 icon 是 string 且看起来像 URL，使用自定义 favicon
 * - 其他: 使用默认 favicon
 */
const displayFavicon = computed(() => {
  const config = toolbarConfig.value?.icon
  if (typeof config === 'string' && (config.startsWith('http') || config.startsWith('data:'))) {
    return config
  }
  return props.tab.favicon
})

/**
 * 实际显示的标题
 * - string: 使用自定义标题
 * - 其他: 使用默认标题
 */
const displayTitle = computed(() => {
  const config = toolbarConfig.value?.title
  if (typeof config === 'string') {
    return config
  }
  return props.tab.title
})

/**
 * 是否使用自定义图标（MDI 图标，非 URL）
 */
const useCustomIcon = computed(() => {
  const config = toolbarConfig.value?.icon
  return typeof config === 'string' && !config.startsWith('http') && !config.startsWith('data:')
})

/**
 * 是否使用自定义 favicon（URL）
 */
const useCustomFavicon = computed(() => {
  const config = toolbarConfig.value?.icon
  return typeof config === 'string' && (config.startsWith('http') || config.startsWith('data:'))
})

// 左侧自定义按钮
const leftButtons = computed(() => toolbarConfig.value?.leftBtns || [])

// 右侧自定义按钮
const rightButtons = computed(() => toolbarConfig.value?.rightBtns || [])

/**
 * 获取按钮的额外属性（排除已知的固定属性）
 * @param btn 按钮配置对象
 * @returns 额外的属性对象
 */
function getButtonAttrs(btn: F2.toolbar.ButtonConfig) {
  const knownProps = new Set(['icon', 'title', 'disabled', 'visible', 'color', 'id'])
  const attrs: Record<string, any> = {}

  for (const key in btn) {
    if (!knownProps.has(key)) {
      attrs[key] = btn[key]
    }
  }

  return attrs
}

// 是否显示固定按钮（仅从 sidebarUi 读取）
const showPinButton = computed(() => {
  return !props.isLeft && props.tab.sidebarUi?.showPinButton !== false
})

// 是否显示最小化按钮（仅从 sidebarUi 读取）
const showMinimizeButton = computed(() => {
  return !props.isLeft && props.tab.sidebarUi?.showMinimizeButton !== false
})

// 是否显示最大化按钮（仅分离窗口显示；仅从 sidebarUi 读取）
const showMaximizeButton = computed(() => {
  if (props.tab.sidebarUi?.showMaximizeButton === false) return false
  return props.tab.isInSeparateWindow
})

// 当前窗口是否最大化
const isMaximized = ref(false)

// 是否显示独立窗口按钮（仅从 sidebarUi 读取）
const showSeparateWindowButton = computed(() => {
  return props.tab.sidebarUi?.showSeparateWindowButton !== false
})

// 是否显示更多菜单项目（仅从 sidebarUi 读取）
const showMoreMenuItems = computed(() => {
  return props.tab.sidebarUi?.showMoreMenuItems !== false
})

// 是否显示关闭按钮（仅从 sidebarUi 读取）
const showCloseButton = computed(() => {
  return props.tab.sidebarUi?.showCloseButton !== false
})

// 处理自定义按钮点击
function handleCustomButtonClick(buttonId: string) {
  _pre_.tab.toolbarButtonClick(buttonId, webContentsId.value)
}

function minimize() {
  _pre_.browser.hideTab(props.tab.id)
}

/**
 * 切换最大化/还原窗口
 */
function toggleMaximize() {
  if (isMaximized.value) {
    _pre_.browser.unmaximizeWindow()
  } else {
    _pre_.browser.maximizeWindow()
  }
}

const { t } = useI18n()

function closes() {
  _pre_.tab.close(webContentsId.value)
}

function setUserAgent() {
  _pre_.tab.toggleUserAgent(webContentsId.value)
}

function toggleSeparateWindow() {
  _pre_.tab.toggleSeparateWindow(webContentsId.value)
}

/**
 * 切换固定状态
 */
function togglePinned() {
  _pre_.tab.togglePinned(webContentsId.value)
}

/**
 * 显示系统级上下文菜单
 */
async function handleContextMenu(event: MouseEvent) {
  event.preventDefault()
  event.stopPropagation()

  await showContextMenu([
    {
      label: `${t('sidebar.contextMenu.goBack')} (&B)(B)`,
      icon: mdiArrowLeft,
      enabled: props.tab.nav.canGoBack,
      cb: () => _pre_.tab.back(webContentsId.value)
    },
    {
      label: `${t('sidebar.contextMenu.goForward')} (&F)(F)`,
      icon: mdiArrowRight,
      enabled: props.tab.nav.canGoForward,
      cb: () => _pre_.tab.forward(webContentsId.value)
    },
    {
      label: `${props.tab.nav.isLoading ? t('sidebar.contextMenu.stop') : t('sidebar.contextMenu.refresh')} (&R)(R)`,
      icon: props.tab.nav.isLoading ? mdiClose : mdiRefresh,
      cb: () =>
        props.tab.nav.isLoading
          ? _pre_.tab.stop(webContentsId.value)
          : _pre_.tab.refresh(webContentsId.value)
    },
    {
      label: `${t('sidebar.contextMenu.goHome')} (&H)(H)`,
      icon: mdiHomeOutline,
      visible: Boolean(props.homeUrl),
      cb: () => _pre_.tab.navigate(props.homeUrl, webContentsId.value)
    },
    { type: 'separator' },
    {
      label: `${props.tab.isMobile ? t('sidebar.contextMenu.desktopMode') : t('sidebar.contextMenu.mobileMode')} (&M)(M)`,
      icon: props.tab.isMobile ? mdiMonitorSmall : mdiCellphone,
      cb: () => setUserAgent()
    },
    { type: 'separator' },
    {
      label: `${props.tab.isInSeparateWindow ? t('sidebar.contextMenu.backToBrowser') : t('sidebar.contextMenu.separateWindow')} (&S)(S)`,
      icon: props.tab.isInSeparateWindow ? mdiImport : mdiExport,
      cb: () => toggleSeparateWindow()
    },
    {
      label: `${props.tab.sidebarConfig?.isPinned ? t('sidebar.contextMenu.unpinTab') : t('sidebar.contextMenu.pinTab')} (&P)(P)`,
      icon: isPinned.value ? mdiPinOutline : mdiPinOffOutline,
      visible: !props.tab.isInSeparateWindow && showPinButton.value,
      cb: () => togglePinned()
    }
  ])
}

const unregisterEsc = register({
  id: `tab-hide-${webContentsId.value}`,
  priority: EscPriority.HIDE,
  onEsc: () => {
    _pre_.browser.hideTab(props.tab.id)
    return true
  }
})

// 监听窗口最大化状态
let unsubscribe: (() => void) | undefined

onMounted(() => {
  // 获取初始最大化状态
  isMaximized.value = _pre_.browser.isWindowMaximized()
  // 订阅最大化状态变更
  unsubscribe = layoutOn('window:maximize-state', (maximized: boolean) => {
    isMaximized.value = maximized
  })
})

onUnmounted(() => {
  unregisterEsc()
})

// 取消订阅窗口最大化状态
onUnmounted(() => {
  if (unsubscribe) unsubscribe()
})
</script>

<template>
  <v-row
    align="center"
    class="pl-2 ma-0 bg-sidebar flex-lg-nowrap rounded-t-lg"
    :style="{
      height: '32px'
    }"
  >
    <!-- 图标或 favicon（支持自定义） -->
    <v-icon
      v-if="shouldShowIcon && (useCustomIcon || (!useCustomFavicon && displayIcon))"
      :icon="displayIcon"
      size="x-small"
    />
    <v-avatar
      v-else-if="shouldShowIcon && (useCustomFavicon || displayFavicon)"
      class="flex-none"
      :image="useCustomFavicon ? displayIcon : displayFavicon"
      size="16"
    />
    <div class="flex-1-1-0 w-0 d-flex align-center overflow-hidden">
      <!-- 标题（支持自定义） -->
      <span v-if="shouldShowTitle" class="text-truncate text-body-2 ml-1 flex-0-1">{{
        displayTitle
      }}</span>

      <v-defaults-provider
        :defaults="{
          VBtn: {
            size: 'small',
            color: '',
            variant: 'text',
            density: 'comfortable',
            class: 'mx-1 app-no-drag'
          }
        }"
      >
        <!-- 左侧自定义按钮（当不显示 icon 和 title 时靠最左边） -->
        <v-btn
          v-for="btn in leftButtons"
          :key="btn.id"
          v-bind="getButtonAttrs(btn)"
          class="flex-0-0"
          :color="btn.color"
          :disabled="btn.disabled"
          :icon="btn.icon"
          :style="{ display: btn.visible === false ? 'none' : undefined }"
          :title="btn.title"
          @click="handleCustomButtonClick(btn.id)"
        ></v-btn>
      </v-defaults-provider>
    </div>

    <v-defaults-provider
      :defaults="{
        VBtn: {
          size: 'small',
          color: '',
          variant: 'text',
          density: 'comfortable',
          class: 'mx-1 app-no-drag'
        }
      }"
    >
      <!-- 右侧自定义按钮 -->
      <v-btn
        v-for="btn in rightButtons"
        :key="btn.id"
        v-bind="getButtonAttrs(btn)"
        :color="btn.color"
        :disabled="btn.disabled"
        :icon="btn.icon"
        :style="{ display: btn.visible === false ? 'none' : undefined }"
        :title="btn.title"
        @click="handleCustomButtonClick(btn.id)"
      >
      </v-btn>

      <FindInPage class="app-no-drag" :tab="tab" />
      <TranslateMenu :tab="tab" />
      <v-btn
        v-if="showMoreMenuItems"
        class="mx-1"
        density="comfortable"
        :icon="mdiDotsVertical"
        size="small"
        variant="text"
        @click="handleContextMenu"
        @contextmenu="handleContextMenu"
      />
      <v-btn
        v-if="!tab.isInSeparateWindow && showPinButton"
        :color="isPinned ? 'primary' : ''"
        data-testid="webContent-mdiDotsVerticalpinTab"
        :icon="isPinned ? mdiPinOutline : mdiPinOffOutline"
        :title="isPinned ? t('sidebar.contextMenu.unpinTab') : t('sidebar.contextMenu.pinTab')"
        @click="togglePinned()"
      />
      <v-btn
        v-if="showSeparateWindowButton"
        data-testid="webContent-mdiArrowmdiImport"
        :icon="tab.isInSeparateWindow ? mdiImport : mdiExport"
        :title="
          tab.isInSeparateWindow
            ? t('sidebar.contextMenu.backToBrowser')
            : t('sidebar.contextMenu.separateWindow')
        "
        @click="toggleSeparateWindow()"
      />

      <!-- 最小化按钮（可配置） -->
      <v-btn
        v-if="showMinimizeButton"
        data-testid="webContent-mdiMinus"
        :icon="mdiMinus"
        @click="minimize"
      />
      <!-- 最大化/还原按钮（仅分离窗口显示） -->
      <v-btn
        v-if="showMaximizeButton"
        data-testid="webContent-mdiWindowMaximize"
        :icon="isMaximized ? mdiWindowRestore : mdiWindowMaximize"
        @click="toggleMaximize"
      />

      <!-- 关闭按钮（可配置） -->
      <v-btn
        v-if="showCloseButton"
        data-testid="webContent-mdiClose"
        :icon="mdiClose"
        @click="closes"
      />
    </v-defaults-provider>
  </v-row>
</template>

<i18n>
{
  "zhHans": {
    "sidebar": {
      "contextMenu": {
        "goBack": "后退",
        "goForward": "前进",
        "refresh": "刷新",
        "stop": "停止",
        "goHome": "主页",
        "mobileMode": "移动端模式",
        "desktopMode": "桌面端模式",
        "separateWindow": "分离窗体",
        "backToBrowser": "回到浏览器",
        "pinTab": "固定标签页",
        "unpinTab": "取消固定标签页",
        "alwaysOnTop": "窗口置顶",
        "cancelAlwaysOnTop": "取消置顶"
      }
    }
  },
  "en": {
    "sidebar": {
      "contextMenu": {
        "goBack": "Go Back",
        "goForward": "Go Forward",
        "refresh": "Refresh",
        "stop": "Stop",
        "goHome": "Home",
        "mobileMode": "Mobile Mode",
        "desktopMode": "Desktop Mode",
        "separateWindow": "Separate Window",
        "backToBrowser": "Back to Browser",
        "pinTab": "Pin Tab",
        "unpinTab": "Unpin Tab",
        "alwaysOnTop": "Always on Top",
        "cancelAlwaysOnTop": "Cancel Always on Top"
      }
    }
  }
}
</i18n>
